"""
投资团队演示脚本
运行完整的投资团队决策流程
"""
import os
import sys
import logging
from pathlib import Path

# 将项目根目录添加到路径
sys.path.append(str(Path(__file__).parent.parent))

# 导入必要的模块
from loguru import logger
from workflows.investment_team import create_investment_team

def setup_logging():
    """设置日志"""
    # 创建logs目录
    logs_dir = Path(__file__).parent.parent / "logs"
    logs_dir.mkdir(exist_ok=True)
    
    # 配置loguru
    logger.remove()  # 移除默认处理程序
    logger.add(
        sys.stdout,
        level="INFO",
        format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
    )
    logger.add(
        logs_dir / "abot_{time:YYYY-MM-DD}.log",
        level="DEBUG",
        rotation="1 day",
        retention="30 days",
        format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level} | {name}:{function}:{line} - {message}"
    )

def main():
    """主函数"""
    # 设置日志
    setup_logging()
    
    logger.info("开始运行A股投资团队演示")
    
    try:
        # 创建投资团队
        investment_team = create_investment_team()
        
        # 运行工作流
        result = investment_team.run()
        
        # 输出结果
        logger.info("=== 投资决策结果 ===")
        
        # 展示市场分析
        market_analysis = result.get("market_analysis", {})
        logger.info(f"市场分析: {market_analysis.get('market_trend', '未知')} ({market_analysis.get('date', '未知')})")
        
        # 展示投资策略
        strategy = result.get("investment_strategy", {})
        logger.info(f"投资策略: {strategy.get('market_view', '未知')}")
        logger.info(f"资产配置: {strategy.get('asset_allocation', {})}")
        
        # 展示交易决策
        decisions = result.get("decisions", {})
        trades = decisions.get("trades", [])
        logger.info(f"交易决策: {len(trades)} 笔交易")
        for i, trade in enumerate(trades):
            logger.info(f"  交易 {i+1}: {trade.get('type')} {trade.get('stock_code')} × {trade.get('amount')} @ {trade.get('price')}")
        
        # 展示执行结果
        execution = result.get("execution_results", {})
        logger.info(f"交易执行: 成功率 {execution.get('success_rate', 0)*100}%")
        
        # 展示绩效评估
        performance = result.get("performance", {})
        logger.info(f"投资绩效: 日收益率 {performance.get('daily_return', 0)*100}%, Alpha {performance.get('alpha', 0)*100}%")
        
        # 保存结果
        output_dir = Path(__file__).parent.parent / "outputs"
        output_dir.mkdir(exist_ok=True)
        # 构建文件名
        from datetime import datetime
        date_str = datetime.now().strftime("%Y%m%d")
        output_file = output_dir / f"investment_result_{date_str}.json"
        
        # 将CrewOutput对象转换为可序列化的字典
        import json
        
        # 自定义JSON编码器处理CrewOutput
        class CustomJSONEncoder(json.JSONEncoder):
            def default(self, o):
                # 如果是CrewOutput对象，转换为字典
                if hasattr(o, '__dict__'):
                    return o.__dict__
                # 处理其他不可序列化类型
                try:
                    return str(o)
                except:
                    return None
        
        # 准备可序列化的数据
        serializable_result = {}
        
        # 从CrewOutput提取数据
        try:
            # 如果是CrewOutput对象
            if hasattr(result, 'raw'):
                serializable_result = {"raw_output": str(result.raw)}
                
                # 尝试将已有的数据合并
                if isinstance(result, dict):
                    for key, value in result.items():
                        if key != 'raw':
                            serializable_result[key] = value
            else:
                # 如果已经是字典形式
                serializable_result = dict(result)
        except:
            # 最坏情况：完全无法序列化，仅保存字符串表示
            serializable_result = {"output": str(result)}
            
        with open(output_file, "w", encoding="utf-8") as f:
            json.dump(serializable_result, f, indent=2, ensure_ascii=False, cls=CustomJSONEncoder)
            json.dump(result, f, indent=2, ensure_ascii=False)
        
        logger.info(f"结果已保存到 {output_file}")
        
    except Exception as e:
        logger.error(f"运行过程中发生错误: {e}")
        import traceback
        logger.error(traceback.format_exc())
    
    logger.info("A股投资团队演示完成")

if __name__ == "__main__":
    main()